package cn.iocoder.yudao.module.wms.controller.admin.warehouse;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.wms.dal.dataobject.warehouse.PositionDO;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.wms.controller.admin.warehouse.vo.*;
import cn.iocoder.yudao.module.wms.dal.dataobject.warehouse.WarehouseDO;
import cn.iocoder.yudao.module.wms.service.warehouse.WarehouseService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 仓库")
@RestController
@RequestMapping("/wms/warehouse")
@Validated
public class WarehouseController {

    @Resource
    private WarehouseService warehouseService;

    @PostMapping("/create")
    @Operation(summary = "创建仓库")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:create')")
    public CommonResult<Long> createWarehouse(@Valid @RequestBody WarehouseSaveReqVO createReqVO) {
        return success(warehouseService.createWarehouse(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新仓库")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:update')")
    public CommonResult<Boolean> updateWarehouse(@Valid @RequestBody WarehouseSaveReqVO updateReqVO) {
        warehouseService.updateWarehouse(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除仓库")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('wms:warehouse:delete')")
    public CommonResult<Boolean> deleteWarehouse(@RequestParam("id") Long id) {
        warehouseService.deleteWarehouse(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得仓库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:query')")
    public CommonResult<WarehouseRespVO> getWarehouse(@RequestParam("id") Long id) {
        WarehouseDO warehouse = warehouseService.getWarehouse(id);
        return success(BeanUtils.toBean(warehouse, WarehouseRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得仓库分页")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:query')")
    public CommonResult<PageResult<WarehouseRespVO>> getWarehousePage(@Valid WarehousePageReqVO pageReqVO) {
        PageResult<WarehouseDO> pageResult = warehouseService.getWarehousePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, WarehouseRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出仓库 Excel")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:export')")
    @OperateLog(type = EXPORT)
    public void exportWarehouseExcel(@Valid WarehousePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<WarehouseDO> list = warehouseService.getWarehousePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "仓库.xls", "数据", WarehouseRespVO.class,
                        BeanUtils.toBean(list, WarehouseRespVO.class));
    }

    @GetMapping("/tree")
    @Operation(summary = "获得仓库树形结构")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:query')")
    public CommonResult<List<WarehouseTreeRespVO>> getWarehouse() {
        List<WarehouseDO> warehouseList = warehouseService.getWarehouseList();
        List<WarehouseTreeRespVO> respVO = BeanUtils.toBean(warehouseList, WarehouseTreeRespVO.class);
        Set<Long> warehouseIds = CollectionUtils.convertSet(warehouseList, WarehouseDO::getId);
        if (CollectionUtil.isNotEmpty(warehouseIds)) {
            List<PositionDO> positions = warehouseService.getPositionList(warehouseIds);
            if (CollectionUtil.isNotEmpty(positions)) {
                List<WarehouseTreeRespVO.Position> positionList = BeanUtils.toBean(positions, WarehouseTreeRespVO.Position.class);
                Map<Long, List<WarehouseTreeRespVO.Position>> positionMap = CollectionUtils.convertMultiMap(positionList, WarehouseTreeRespVO.Position::getWarehouseId);
                respVO.forEach(item -> {
                    if (positionMap.containsKey(item.getId())) {
                        item.setChildren(positionMap.get(item.getId()));
                    }
                });
            }
        }
        return success(respVO);
    }



    // ==================== 子表（库位） ====================

    @GetMapping("/position/page")
    @Operation(summary = "获得库位分页")
    @Parameter(name = "warehouseId", description = "仓库")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:query')")
    public CommonResult<PageResult<PositionDO>> getPositionPage(PageParam pageReqVO,
                                                                @RequestParam("warehouseId") Long warehouseId) {
        return success(warehouseService.getPositionPage(pageReqVO, warehouseId));
    }

    @PostMapping("/position/create")
    @Operation(summary = "创建库位")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:create')")
    public CommonResult<Long> createPosition(@Valid @RequestBody PositionDO position) {
        return success(warehouseService.createPosition(position));
    }

    @PutMapping("/position/update")
    @Operation(summary = "更新库位")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:update')")
    public CommonResult<Boolean> updatePosition(@Valid @RequestBody PositionDO position) {
        warehouseService.updatePosition(position);
        return success(true);
    }

    @DeleteMapping("/position/delete")
    @Parameter(name = "id", description = "编号", required = true)
    @Operation(summary = "删除库位")
    @PreAuthorize("@ss.hasPermission('wms:warehouse:delete')")
    public CommonResult<Boolean> deletePosition(@RequestParam("id") Long id) {
        warehouseService.deletePosition(id);
        return success(true);
    }

	@GetMapping("/position/get")
	@Operation(summary = "获得库位")
	@Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('wms:warehouse:query')")
	public CommonResult<PositionDO> getPosition(@RequestParam("id") Long id) {
	    return success(warehouseService.getPosition(id));
	}

}